package com.travel.common.handel;


import com.travel.common.base.Resp;
import com.travel.common.exception.LogicException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常拦截器，拦截参数校验异常
 *
 * @author fengchu
 * @date Created in 下午5:35 2018/7/20
 */
@Slf4j
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Resp handle(ConstraintViolationException exception) {

        String message = exception.getMessage();

        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {

            String[] propertyPath = item.getPropertyPath().toString().split("\\.");
            String methodName = propertyPath[0];
            String parameterName = propertyPath[1].replace("arg", "").replace(methodName, "");
            message = parameterName + " : " + item.getMessage();
        }

        return Resp.error(message, HttpStatus.BAD_REQUEST.value());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public Resp handle(MethodArgumentNotValidException exception) {

        String message = exception.getBindingResult().getFieldError().getField() + " : " + exception.getBindingResult().getFieldError().getDefaultMessage();

        return Resp.error(message, HttpStatus.BAD_REQUEST.value());
    }

    @ExceptionHandler(LogicException.class)
    @ResponseStatus(HttpStatus.OK)
    public Resp handle(LogicException exception) {

        return Resp.error(exception.getMsg(), exception.getCode());
    }




    /*@ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    public Resp handle(Exception exception) {

        exception.printStackTrace();

        log.error(exception.getMessage(), exception);

        return Resp.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
    }*/

}